package com.hiof.servercommunication.background.job;

import com.hiof.utility.Utility;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by IntelliJ IDEA.
 * User: manish
 * Date: 4/1/12
 * Time: 12:46 PM
 * To change this template use File | Settings | File Templates.
 */
public class TimerJobManager {

    private static TimerJobManager instance = new TimerJobManager();
    private List<AbstractJob> timerJobs = new ArrayList<AbstractJob>();
    private JobThreadQueue jobQueue;
    private static final int TIME_INTERVAL = 1 * 60 * 1000;// 5 * 60 * 1000;//5 minutes
    Timer serverSendTimer;

    public static TimerJobManager getInstance() {
        return instance;
    }

    private TimerJobManager() {
        jobQueue = JobThreadQueue.getInstance();
        startTimerJob();
    }

    public void addTimerJob(AbstractJob job) {
        timerJobs.add(job);
    }

    public void startTimerJob() {
        serverSendTimer = new Timer(true);
        serverSendTimer.scheduleAtFixedRate(jobTimerTask, 0, TIME_INTERVAL);
    }

    public void stopTimerJob() {
        if (serverSendTimer != null) {
            serverSendTimer.cancel();
        }
    }

    TimerTask jobTimerTask = new TimerTask() {
        public void run() {
            for (AbstractJob job : timerJobs) {
                Utility.debug(this.getClass().toString(), "Timer Job added");
                jobQueue.addJob(job);
            }
        }
    };
}
